package dao.impl;

import dao.ProductDao;
import domain.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.C3P0Utils;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/2/25 9:21
 */
public class ProductDaoImpl implements ProductDao {
    QueryRunner runnr = new QueryRunner(C3P0Utils.getDateSourse());
    @Override
    public List<Product> findAll() {
        String sql = "SELECT * FROM product";
        try {
            return runnr.query(sql,new BeanListHandler<Product>(Product.class));
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int deleteProduct(int pid) {
        String sql = "delete from product where pid=?";
        try {
            runnr.update(sql,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void editProduct(Product p) {
        String sql = "update product set pname=?,marketprice=?,shopprice=?,image=?,pdesc=?,ishot=? where pid=?";
        Object[] canshu = {
                p.getPname(),
                p.getMarketprice(),
                p.getShopprice(),
                p.getImage(),
                p.getPdesc(),
                p.getIshot(),
                p.getPid()
        };

        try {
            runnr.update(sql,canshu);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Product> productAll(String pid) {

        String sql = "SELECT * FROM product where pid="+pid;
        try {
            return runnr.query(sql,new BeanListHandler<Product>(Product.class));
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addProducct(Product product) {
        String sql = "insert into product(pname,marketprice,shopprice,ishot,pdesc) Value=(?,?,?,?,?)";
        Object[] tainjia={
                product.getPname(),
                product.getMarketprice(),
                product.getShopprice(),
                product.getImage(),
                product.getPdesc(),
                product.getIshot()
        };
        try {
            int update = runnr.update(sql, tainjia);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
